package de.fhffm.scs.simulator.driver;

import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.TimeUnit;

import de.fhffm.scs.simulator.data.BloodSugarLevel;
import de.fhffm.scs.simulator.hardware.SensorHardware;
import de.fhffm.scs.simulator.scheduler.Scheduler;

public class SensorDriverImpl extends Observable implements SensorDriver {

	SensorHardware hwSensor;
	Scheduler scheduler;
	TimeUnit timeUnit;
	int interval;

	BloodSugarLevel lastValueRead;

	public SensorDriverImpl(SensorHardware hardwareSensor, Scheduler scheduler,
			TimeUnit timeUnit, int interval) {
		if (hardwareSensor == null || scheduler == null || timeUnit == null
				|| interval < 1) {
			throw new IllegalArgumentException();
		}
		this.hwSensor = hardwareSensor;
		this.timeUnit = timeUnit;
		this.interval = interval;
		this.scheduler = scheduler;
	}

	@Override
	public BloodSugarLevel getBloodSugarLevel() {
		return lastValueRead;
	}

	public SensorHardware getSensorHardware() {
		return hwSensor;
	}

	public void setBloodsugarlevel(BloodSugarLevel bloodsugarlevel) {
		this.lastValueRead = bloodsugarlevel;
	}

	@Override
	public void run() {
		Thread currentThread = Thread.currentThread();

		while (!currentThread.isInterrupted()) {
			try {
				scheduler.sleep(timeUnit, interval);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			BloodSugarLevel tempValue = hwSensor.getBloodSugarLevel();

			if (lastValueRead != tempValue) {
				lastValueRead = tempValue;
				setChanged();
				notifyObservers(lastValueRead);
			}
		}
	}

	@Override
	public void notifyValueRead() {
		this.setChanged();
		this.notifyObservers(lastValueRead);
	}

	@Override
	public void addObserver(Observer o) {
		super.addObserver(o);
	}
}
